﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO.Ports;
using System.Threading;
using System.Globalization;
namespace ModemGSM
{
    static class GSMAPI
    {
        private static string SupressResult(string Cmd)
        {
            int pos = Cmd.IndexOf(":");
            if (pos < 0)
            {
                return Cmd;
            }
            return Cmd.Substring(pos + 1);
        }
        
        private static string SupressCR(string Cmd)
        {
            Cmd = Cmd.Replace("\n", "");
            Cmd = Cmd.Replace("\r", "");
            return Cmd;
        }

        private static string SupressOK(string Cmd)
        {
            Cmd = Cmd.Replace("OK", "");
            return Cmd;
        }

        private static string SupressDefaut(string Cmd)
        {
            Cmd = SupressResult(Cmd);
            Cmd = SupressCR(Cmd);
            Cmd = SupressOK(Cmd);
            return Cmd.Trim();
        }

        private static string SupressDelimtStr(string Cmd)
        {
            Cmd = Cmd.Replace((char)34, new Char());
            Cmd = Cmd.Replace("\0", "");
            return Cmd;
        }

        static public GSMIndicator GetIndicators(Modem SerialPort)
        {
            GSMIndicator result = new GSMIndicator();
            string outputlst = "";
            string outputval = "";
            try
            {
                SerialPort.SendCommand(ATCOMMAND.EchoOff);
                outputlst = SerialPort.SendCommand(ATCOMMAND.IndicatorControl_CMD + ATCOMMAND.ExistCommand);
                outputlst = SupressDefaut(outputlst);
                outputlst = SupressDelimtStr(outputlst);
                outputlst = outputlst.Replace("(", "");
                outputlst = outputlst.Replace(")", "");
                outputlst = outputlst.Replace("-", ",");
                if (!outputlst.Contains("ERROR"))
                {
                    string[] listName = outputlst.Split(',');
                    outputval = SerialPort.SendCommand(ATCOMMAND.IndicatorControlValues);
                    outputval = SupressDefaut(outputval);
                    if (!outputval.Contains("ERROR"))
                    {
                        string[] listVal = outputval.Split(',');

                        bool bName = true;
                        bool bMin = false;
                        bool bMax = false;
                        string Name = "";
                        RangerValue it = null;
                        int posv = -1;
                        for (int i = 0; i < listName.Length; i++)
                        {
                            if (bName)
                            {
                                it = new RangerValue();
                                Name = listName[i].Trim();
                                bName = false;
                                bMin = true;
                                bMax = false;
                            }
                            else if (bMin)
                            {
                                it.Min = int.Parse(listName[i].Trim());
                                bName = false;
                                bMin = false;
                                bMax = true;
                            }
                            else if (bMax)
                            {
                                it.Max = int.Parse(listName[i].Trim());
                                posv++;
                                it.value = int.Parse(listVal[posv].Trim());
                                bName = true;
                                bMin = false;
                                bMax = false;
                                if (Name.ToLower() == "battchg")
                                {
                                    result.Battchg = it;
                                }
                                else if (Name.ToLower() == "signal")
                                {
                                    result.Signal = it;
                                }
                                else if (Name.ToLower() == "service")
                                {
                                    result.Service = it;
                                }
                                else if (Name.ToLower() == "message")
                                {
                                    result.Message = it;
                                }
                                else if (Name.ToLower() == "call")
                                {
                                    result.Call = it;
                                }
                                else if (Name.ToLower() == "vox")
                                {
                                    result.Vox = it;
                                }
                                else if (Name.ToLower() == "roam")
                                {
                                    result.Roam = it;
                                }
                                else if (Name.ToLower() == "smsfull")
                                {
                                    result.SMSFull = it;
                                }
                            }
                        }
                    }
                    else
                    {
                        SerialPort.SetError("ERROR READ INDICATOR");
                    }
                }
                else
                {
                    SerialPort.SetError("ERROR READ INDICATOR");
                    result = new GSMIndicator();
                }
            }
            catch (Exception e)
            {
                SerialPort.SetError(e.Message);
                result = new GSMIndicator();
            }
            return result;
        }

        static public List<PhoneStorage> GetListPhones(Modem SerialPort,string CharSet, StorageReadEnum Storage,int Start, int End)
        {
            SerialPort.SendCommand(ATCOMMAND.EchoOff);
            List<PhoneStorage> RET = new List<PhoneStorage>();
            string result = "";
            try
            {
                if (SetCharSet(SerialPort, CharSet))
                {
                    if (Storage == StorageReadEnum.SIM)
                    {
                        result = SerialPort.SendCommand(ATCOMMAND.PhoneBookStorageSIM);
                    }
                    else if (Storage == StorageReadEnum.Phone)
                    {
                        result = SerialPort.SendCommand(ATCOMMAND.PhoneBookStorageMEM);
                    }
                    else
                    {
                        result = "ERROR";
                    }
                    result = SupressDefaut(result);
                    if (!result.Contains("ERROR"))
                    {
                        result = SerialPort.SendCommand(ATCOMMAND.PhoneBookRead + Start.ToString() + "," + End.ToString());
                        result = SupressDefaut(result);
                        result = SupressDelimtStr(result);
                        result = result.Replace(ATCOMMAND.StrPhoneBookDelimt, ",");
                        if (!result.Contains("ERROR"))
                        {
                            if (result.StartsWith(","))
                            {
                                result = result.Substring(1);
                            }
                            string[] param = result.Split(',');
                            int pos = 0;
                            while (pos < param.Length && param.Length >=3)
                            {
                                PhoneStorage item = new PhoneStorage();
                                item.Index = int.Parse(param[pos].Trim());
                                item.Number = param[pos + 1].Trim();
                                item.Type = int.Parse(param[pos + 2].Trim());
                                item.Name = param[pos + 3].Trim();
                                if (item.Name != "" && item.Number != "")
                                {
                                    RET.Add(item);
                                }
                                pos += 4;
                            }
                        }
                        else
                        {
                            SerialPort.SetError("ERROR READ PHONEBOOK");
                        }
                    }
                    else
                    {
                        SerialPort.SetError("ERROR READ PHONEBOOK");
                    }
                }
            }
            catch (Exception e)
            {
                SerialPort.SetError(e.Message);
            }
            return RET;
        }

        static public RangerValue GetSIMPhoneRange(Modem SerialPort)
        {
            RangerValue RET = new RangerValue();
            string result = "";
            try
            {
                SerialPort.SendCommand(ATCOMMAND.EchoOff);
                result = SerialPort.SendCommand(ATCOMMAND.PhoneBookStorageSIM);
                result = SupressDefaut(result);
                if (!result.Contains("ERROR"))
                {
                    result = SerialPort.SendCommand(ATCOMMAND.PhoneBookValue);
                    result = SupressDefaut(result);
                    result = SupressDelimtStr(result);
                    if (!result.Contains("ERROR"))
                    {
                        RET.Min = 1;
                        string[] param = result.Split(',');
                        RET.value = int.Parse(param[1].Trim());
                        RET.Max = int.Parse(param[2].Trim());
                    }
                    else
                    {
                        SerialPort.SetError("ERROR READ PHONE RANGER SIM");
                    }
                }
                else
                {
                    SerialPort.SetError("ERROR READ PHONE RANGER SIM");
                }
            }
            catch (Exception e)
            {
                SerialPort.SetError(e.Message);
            }
            return RET;
        }

        static public RangerValue GetMEMPhoneRange(Modem SerialPort)
        {
            RangerValue RET = new RangerValue();
            string result = "";
            try
            {
                SerialPort.SendCommand(ATCOMMAND.EchoOff);
                result = SerialPort.SendCommand(ATCOMMAND.PhoneBookStorageMEM);
                result = SupressDefaut(result);
                if (!result.Contains("ERROR"))
                {
                    result = SerialPort.SendCommand(ATCOMMAND.PhoneBookValue);
                    result = SupressDefaut(result);
                    result = SupressDelimtStr(result);
                    if (!result.Contains("ERROR"))
                    {
                        RET.Min = 1;
                        string[] param = result.Split(',');
                        RET.value = int.Parse(param[1].Trim());
                        RET.Max = int.Parse(param[2].Trim());
                    }
                    else
                    {
                        SerialPort.SetError("ERROR READ PHONE RANGER MEM");
                    }
                }
                else
                {
                    SerialPort.SetError("ERROR READ PHONE RANGER MEM");
                }
            }
            catch (Exception e)
            {
                SerialPort.SetError(e.Message);
            }
            return RET;
        }

        static public int? GetBatteryLevel(Modem SerialPort,int Minvalue)
        {
            return InternalGetBatteryLevel(SerialPort, Minvalue);
        }
        
        static public int? GetBatteryLevel(Modem SerialPort)
        {
            return InternalGetBatteryLevel(SerialPort, 0);
        }
  
        static private int? InternalGetBatteryLevel(Modem SerialPort, int minvalue)
        {
            string result = "";
            try
            {
                SerialPort.SendCommand(ATCOMMAND.EchoOff);
                result = SerialPort.SendCommand(ATCOMMAND.BatteryLevel_CMD);
                result = SupressDefaut(result);
                if (!result.Contains("ERROR"))
                {
                    int baux = int.Parse(result.Split(',')[1].Trim());
                    if (baux > 100)
                    {
                        baux = 100;
                    }
                    if (baux < minvalue)
                    {
                        baux = minvalue;
                    }
                    baux = baux - minvalue;
                    result = (baux * 100/(100-minvalue)).ToString("###",new CultureInfo("en-US"));
                }
                else
                {
                    SerialPort.SetError("ERROR READ BATTERY");
                }
            }
            catch (Exception e)
            {
                SerialPort.SetError(e.Message);
            }
            if (SerialPort.Error != "")
            {
                return null;
            }
            if (result == "")
            {
                return null;
            }
            return int.Parse(result.Trim());
        }

        static public string GetPreferredOperator(Modem SerialPort)
        {
            string result = "";
            try
            {
                SerialPort.SendCommand(ATCOMMAND.EchoOff);
                result = SerialPort.SendCommand(ATCOMMAND.PreferredOperatorValue);
                result = SupressDefaut(result);
                result = SupressDelimtStr(result);
                if (!result.Contains("ERROR"))
                {
                    string[] param = result.Split(',');
                    foreach (string item in param)
                    {
                        if (item.Trim() != "0" && item.Trim().Length > 0)
                        {
                            result = item.Trim();
                        }
                    }
                }
                else
                {
                    SerialPort.SetError("ERROR READ PREFERRED OPERATOR");
                }
            }
            catch (Exception e)
            {
                SerialPort.SetError(e.Message);
            }
            return result.Trim();
        }

        static public decimal? GetSignalQuality(Modem SerialPort)
        {
            string result = "";
            try
            {
                SerialPort.SendCommand(ATCOMMAND.EchoOff);
                result = SerialPort.SendCommand(ATCOMMAND.SignalQuality_CMD);
                result = SupressDefaut(result);
                if (!result.Contains("ERROR"))
                {
                    result = result.Split(',')[0].Trim();
                    result = (int.Parse(result.Trim()) * 3.225).ToString("#.##");
                    result = result.Replace(",", ".");
                }
                else
                {
                    SerialPort.SetError("ERROR READ SIGNAL QUALITY");
                }
            }
            catch (Exception e)
            {
                SerialPort.SetError(e.Message);
            }
            if (SerialPort.Error != "")
            {
                return null;
            }
            if (result.Trim() == "")
            {
                result = null;
            }
            return decimal.Parse(result,new System.Globalization.CultureInfo("en-US"));
        }

        static public string GetIMSI(Modem SerialPort)
        {
            string result = "";
            try
            {
                SerialPort.SendCommand(ATCOMMAND.EchoOff);
                result = SerialPort.SendCommand(ATCOMMAND.IMSI_CMD);
                result = SupressDefaut(result);
                if (result.Contains("ERROR"))
                {
                    SerialPort.SetError("ERROR READ MODEL");
                }
            }
            catch (Exception e)
            {
                SerialPort.SetError(e.Message);
                result = "";
            }
            return result.Trim();
        }

        static public string GETIMEI(Modem SerialPort)
        {
            string result = "";
            try
            {
                SerialPort.SendCommand(ATCOMMAND.EchoOff);
                result = SerialPort.SendCommand(ATCOMMAND.IMEI_CMD);
                result = SupressDefaut(result);
                if (result.Contains("ERROR"))
                {
                    SerialPort.SetError("ERROR READ MODEL");
                }
            }
            catch (Exception e)
            {
                SerialPort.SetError(e.Message);
                result = "";
            }
            return result.Trim();
        }

        static public bool SetLineIdentification(Modem SerialPort, bool On)
        {
            string result = "";
            try
            {
                SerialPort.SendCommand(ATCOMMAND.EchoOff);
                if (On)
                {
                    result = SerialPort.SendCommand(ATCOMMAND.LineIdentificationWrite + "1");
                }
                else
                {
                    result = SerialPort.SendCommand(ATCOMMAND.LineIdentificationWrite + "0");
                }
                result = SupressDefaut(result);
                if (result.Contains("ERROR"))
                {
                    SerialPort.SetError("ERROR WRITE DATE AND TIME");
                }
            }
            catch (Exception e)
            {
                SerialPort.SetError(e.Message);
                return false;
            }
            if (SerialPort.Error == "")
            {
                return true;
            }
            return false;
        }

        static public LineIdentification GetLineIdentification(Modem SerialPort)
        {
            LineIdentification ret = new LineIdentification();
            ret.Enabled = false;
            ret.Provisioned = null;
            string result = "";
            try
            {
                SerialPort.SendCommand(ATCOMMAND.EchoOff);
                result = SerialPort.SendCommand(ATCOMMAND.LineIdentification_CMD + ATCOMMAND.ExistCommand);
                if (!result.Contains("ERROR"))
                {
                    result = SerialPort.SendCommand(ATCOMMAND.LineIdentificationValue);
                }
                result = SupressDefaut(result);
                if (!result.Contains("ERROR"))
                {
                    string[] param = result.Split(',');
                    ret.Enabled = param[0].Trim() == "1" ? true : false;
                    if (param[1].Trim() == "1")
                    {
                        ret.Provisioned = true;
                    }
                    if (param[1].Trim() == "0")
                    {
                        ret.Provisioned = false;
                    }
                }
                else
                {
                    SerialPort.SetError("ERROR READ LINE IDENTIFICATION");
                }
            }
            catch (Exception e)
            {
                SerialPort.SetError(e.Message);
            }
            return ret;
        }

        static public string GetModel(Modem SerialPort)
        {
            string result = "";
            try
            {
                SerialPort.SendCommand(ATCOMMAND.EchoOff);
                result = SerialPort.SendCommand(ATCOMMAND.Model_CMD);
                result = SupressDefaut(result);
                if (result.Contains("ERROR"))
                {
                    SerialPort.SetError("ERROR READ MODEL");
                }
            }
            catch (Exception e)
            {
                SerialPort.SetError(e.Message);
                result = "";
            }
            return result.Trim();
        }

        static public StoragesSMS GetStorageSMS(Modem SerialPort)
        {
            StoragesSMS ret = new StoragesSMS();
            string result = "";
            try
            {
                SerialPort.SendCommand(ATCOMMAND.EchoOff);
                result = SerialPort.SendCommand(ATCOMMAND.SMSStorage_CMD + ATCOMMAND.ExistCommand);
                if (result.Contains("ERROR"))
                {
                    SerialPort.SetError("ERROR READ STORAGES SMS");
                }
                else
                {
                    result = SupressDefaut(result);
                    result = SupressDelimtStr(result);
                    result = result.Replace("(", "");
                    result = result.Replace(")", "\r");
                    string[] mems = result.Split(new char[]{'\r'}, StringSplitOptions.RemoveEmptyEntries);
                    if (mems.Length >= 3)
                    {
                        string[] param = mems[0].Trim().Split(new char[]{','}, StringSplitOptions.RemoveEmptyEntries);
                        ret.StoReadDelete = new string[param.Length];
                        for (int i = 0; i < param.Length; i++)
                        {
                            ret.StoReadDelete[i] = param[i].Trim();
                        }

                        param = mems[1].Trim().Split(new char[]{','}, StringSplitOptions.RemoveEmptyEntries);
                        ret.StoWriteSend = new string[param.Length];
                        for (int i = 0; i < param.Length; i++)
                        {
                            ret.StoWriteSend[i] = param[i].Trim();
                        }

                        param = mems[2].Trim().Split(new char[]{','}, StringSplitOptions.RemoveEmptyEntries);
                        ret.StoReceiver = new string[param.Length];
                        for (int i = 0; i < param.Length; i++)
                        {
                            ret.StoReceiver[i] = param[i].Trim();
                        }
                        result = SerialPort.SendCommand(ATCOMMAND.SMSStorage_CMD + "?");
                        if (result.Contains("ERROR"))
                        {
                            SerialPort.SetError("ERROR READ STORAGES SMS");
                        }
                        else
                        {
                            result = SupressDefaut(result);
                            result = SupressDelimtStr(result);
                            param = result.Split(new char[]{','}, StringSplitOptions.RemoveEmptyEntries);
                            if (param.Length >= 9)
                            {
                                ret.ReadDelete = param[0].Trim();
                                ret.RangerReadDelete.value = int.Parse("0" + param[1].Trim());
                                ret.RangerReadDelete.Max = int.Parse("0" + param[2].Trim());

                                ret.WriteSend = param[3].Trim();
                                ret.RangerWriteSend.value = int.Parse("0" + param[4].Trim());
                                ret.RangerWriteSend.Max = int.Parse("0" + param[5].Trim());

                                ret.Receiver = param[6].Trim();
                                ret.RangerReceiver.value = int.Parse("0" + param[7].Trim());
                                ret.RangerReceiver.Max = int.Parse("0" + param[8].Trim());
                            
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                SerialPort.SetError(e.Message);
                ret = new StoragesSMS();
            }
            if (SerialPort.Error != "")
            {
                ret = new StoragesSMS();
            }
            return ret;
        }

        static public bool SetStorageSMS(Modem SerialPort, string ReadDelete, string WriteSend, string Receiver)
        {
            bool OkR = false;
            foreach (string item in SerialPort.SMSStorages.StoReadDelete)
            {
                if (item == ReadDelete)
                {
                    OkR = true;
                    break;
                }
            }
            bool OkW = false;
            foreach (string item in SerialPort.SMSStorages.StoReadDelete)
            {
                if (item == WriteSend)
                {
                    OkW = true;
                    break;
                }
            }
            bool OkC = false;
            foreach (string item in SerialPort.SMSStorages.StoReceiver)
            {
                if (item == Receiver)
                {
                    OkC = true;
                    break;
                }
            }
            if (!OkR || !OkW || !OkC)
            {
                return false;
            }
            string result = "";
            bool ret = false;
            try
            {
                SerialPort.SendCommand(ATCOMMAND.EchoOff);
                result = SerialPort.SendCommand(ATCOMMAND.SMSStorage_CMD + "=\"" + ReadDelete + "\",\"" + WriteSend + "\",\"" + Receiver + "\"");
                if (result.Contains("ERROR"))
                {
                    SerialPort.SetError("ERROR READ STORAGES SMS");
                }
                else
                {
                    ret = true;
                }
            }
            catch (Exception e)
            {
                SerialPort.SetError(e.Message);
            }
            if (SerialPort.Error != "")
            {
                ret = false;
            }
            return ret;
        }

        static public string GetCurrentCharSet(Modem SerialPort)
        {
            string result = "";
            try
            {
                SerialPort.SendCommand(ATCOMMAND.EchoOff);
                result = SerialPort.SendCommand(ATCOMMAND.CharSetCurrent);
                result = SupressDefaut(result);
                result = SupressDelimtStr(result);
                if (result.Contains("ERROR"))
                {
                    SerialPort.SetError("ERROR READ CURRENT CHAR SETTING");
                }
            }
            catch (Exception e)
            {
                SerialPort.SetError(e.Message);
                result = "";
            }
            return result.Trim();
        }

        static public List<string> GetListCharSet(Modem SerialPort)
        {
            string result = "";
            List<string> ret = new List<string>();
            try
            {
                SerialPort.SendCommand(ATCOMMAND.EchoOff);
                result = SerialPort.SendCommand(ATCOMMAND.CharSets_CMD + ATCOMMAND.ExistCommand);
                result = SupressDefaut(result);
                result = SupressDelimtStr(result);
                if (!result.Contains("ERROR"))
                {
                    string[] param = result.Split(',');
                    foreach (var item in param)
                    {
                        if (item.Trim().Length > 0)
                        {
                            ret.Add(item.Trim());
                        }
                    }
                }
                else
                {
                    SerialPort.SetError("ERROR READ MODEL");
                }
            }
            catch (Exception e)
            {
                SerialPort.SetError(e.Message);
                ret = new List<string>();
            }
            return ret;
        }

        static public List<SMSStorage> SMSGetListMessageTextFormat(Modem SerialPort, LocationSMS TypeLocaltion)
        {
            string result = "";
            SerialPort.SendCommand(ATCOMMAND.EchoOff);
            List<SMSStorage> ret = new List<SMSStorage>();
            try
            {
                string Loc = "";
                switch (TypeLocaltion)
                {
                    case LocationSMS.All:
                        Loc = ATCOMMAND.SMSTypeALL;
                        break;
                    case LocationSMS.UnRead:
                        Loc = ATCOMMAND.SMSTypeRecUnread;
                        break;
                    case LocationSMS.Read:
                        Loc = ATCOMMAND.SMSTypeRecRead;
                        break;
                    case LocationSMS.Unsent:
                        Loc = ATCOMMAND.SMSTypeStoredUnsent;
                        break;
                    case LocationSMS.Sent:
                        Loc = ATCOMMAND.SMSTypeStoredSent;
                        break;
                }
                result = SerialPort.SendCommand(ATCOMMAND.SMSFormatToText);
                if (!result.Contains("ERROR"))
                {
                    result = SerialPort.SendCommand(ATCOMMAND.SMSListMessage_CMD + "=\"" + Loc + "\"");
                }
                if (!result.Contains("ERROR"))
                {
                    result = result.Replace("OK", "");
                    string[] param = result.Split(new string[]{ATCOMMAND.SMSListMessage_CMD.Replace("AT","")+":"},  StringSplitOptions.RemoveEmptyEntries );
                    foreach (string item in param)
                    {
                        result = SupressCR(item);
                        if (result.Length > 0)
                        {
                            result = SupressDelimtStr(item).Trim();
                            string[] paramMsg = result.Split(new string[]{"\r","\n"},StringSplitOptions.None);
                            string[] DetMsg = paramMsg[0].Split(',');
                            SMSStorage SMS = new SMSStorage();
                            SMS.ID = int.Parse(DetMsg[0].Trim());
                            SMS.Location = TypeLocaltion;
                            if (DetMsg[1].Trim() == ATCOMMAND.SMSTypeRecUnread)
                            {
                                SMS.Location = LocationSMS.UnRead;
                            }
                            else if (DetMsg[1].Trim() == ATCOMMAND.SMSTypeRecRead)
                            {
                                SMS.Location = LocationSMS.Read;
                            }
                            else if (DetMsg[1].Trim() == ATCOMMAND.SMSTypeStoredUnsent)
                            {
                                SMS.Location = LocationSMS.Unsent;
                            }
                            else if (DetMsg[1].Trim() == ATCOMMAND.SMSTypeStoredSent)
                            {
                                SMS.Location = LocationSMS.Sent;
                            }
                            SMS.Number = DetMsg[2].Trim();
                            SMS.PhoneBookName = "";
                            SMS.DateTime = null;
                            SMS.TimeZone = null;
                            if (DetMsg[4].Trim() != "")
                            {
                                string dtaux = DetMsg[4].Trim().Split(' ')[0];
                                string hraux = DetMsg[4].Trim().Split(' ')[1];
                                string[] part = dtaux.Split('/');

                                string[] dtpart = dtaux.Split('/');
                                string[] tzpart = hraux.Split(new char[] { '-', '+' });
                                string[] hrpart = tzpart[0].Split(':');
                                SMS.DateTime = new DateTime(int.Parse(dtpart[0].Trim()), int.Parse(dtpart[1].Trim()), int.Parse(dtpart[2].Trim()), int.Parse(hrpart[0].Trim()), int.Parse(hrpart[1].Trim()), int.Parse(hrpart[2].Trim()));
                                SMS.TimeZone = new TimeSpan(0, int.Parse(tzpart[1].Trim())*15, 0);
                                if (hraux.Contains("-"))
                                {
                                    SMS.TimeZone = SMS.TimeZone.Value.Negate();
                                }
                            }
                            string Message = "";
                            for (int i = 1; i < paramMsg.Length; i++)
                            {
                                if (i == paramMsg.Length - 1 && paramMsg[i] == "OK")
                                {
                                    break;
                                }
                                Message += paramMsg[i];
                                if (i <= DetMsg.Length)
                                {
                                    Message += "\n";
                                }

                            }
                            while (Message.StartsWith("\n"))
                            {
                                Message = Message.Substring(1);
                            }
                            while (Message.StartsWith("\r"))
                            {
                                Message = Message.Substring(1);
                            }
                            while (Message.EndsWith("\r"))
                            {
                                Message = Message.Substring(0, Message.Length - 1);
                            }
                            while (Message.EndsWith("\n"))
                            {
                                Message = Message.Substring(0, Message.Length - 1);
                            }
                            SMS.Message = Message;
                            ret.Add(SMS);
                        }
                    }
                }
                else
                {
                    SerialPort.SetError("ERROR READ SMS LIST MESSAGES");
                }
            }
            catch (Exception e)
            {
                SerialPort.SetError(e.Message);
                ret = new List<SMSStorage>();
            }
            return ret;
        }

        static public bool SMSIsValidFormatText(Modem SerialPort)
        {
            bool value = false;
            string result = "";
            try
            {
                SerialPort.SendCommand(ATCOMMAND.EchoOff);
                result = SerialPort.SendCommand(ATCOMMAND.SMSFormat_CMD + ATCOMMAND.ExistCommand);
                result = SupressDefaut(result);
                result = result.Replace("(","");
                result = result.Replace(")", "");
                if (!result.Contains("ERROR"))
                {
                    string[] param = result.Split(',');
                    value = (param[1].Trim() == "1");
                }
                else
                {
                    SerialPort.SetError("ERROR READ SMS FORMAT TEXT");
                }
            }
            catch (Exception e)
            {
                SerialPort.SetError(e.Message);
                return false;
            }
            if (SerialPort.Error != "")
            {
                return false;
            }
            return value;
        }

        static public bool SMSIsValidFormatPDU(Modem SerialPort)
        {
            bool value = false;
            string result = "";
            try
            {
                SerialPort.SendCommand(ATCOMMAND.EchoOff);
                result = SerialPort.SendCommand(ATCOMMAND.SMSFormat_CMD + ATCOMMAND.ExistCommand);
                result = SupressDefaut(result);
                result = result.Replace("(", "");
                result = result.Replace(")", "");
                if (!result.Contains("ERROR"))
                {
                    string[] param = result.Split(',');
                    value = (param[0].Trim() == "0");
                }
                else
                {
                    SerialPort.SetError("ERROR READ SMS FORMAT PDU");
                }
            }
            catch (Exception e)
            {
                SerialPort.SetError(e.Message);
                return false;
            }
            if (SerialPort.Error != "")
            {
                return false;
            }
            return value;
        }

        static public int SMSMessageSendText(Modem SerialPort, string Number, string Mensage, bool SaveMessage, string CharSet)
        {
            string result = "";
            int value = -1;
            try
            {
                SerialPort.SendCommand(ATCOMMAND.EchoOff);
                if (CharSet != "")
                {
                    result = SerialPort.SendCommand(ATCOMMAND.CharSetWrite + "\"" + CharSet + "\"");
                }
                if (!result.Contains("ERROR"))
                {
                    result = SerialPort.SendCommand(ATCOMMAND.SMSFormatToText);
                }
               if (!result.Contains("ERROR"))
                {
                    if (SaveMessage)
                    {
                        result = SerialPort.SendCommandWithContinue(ATCOMMAND.SMSWriteMessageStorage_CMD + "=\"" + Number + "\"");
                    }
                    else
                    {
                        result = SerialPort.SendCommandWithContinue(ATCOMMAND.SMSSentMessage_CMD + "=\"" + Number + "\"");
                    }
                    Thread.Sleep(50);
                    if (!result.Contains("ERROR"))
                    {
                        result = SerialPort.SendContinueCommand(Mensage + (Char)26);
                    }
                    if (!result.Contains("ERROR"))
                    {
                        result = SupressDefaut(result);
                        value = int.Parse(result);
                        if (SaveMessage)
                        {
                            int valueSto = value;
                            result = SerialPort.SendCommand(ATCOMMAND.SMSSentMessageStorage_CMD + "=" + value);
                            result = SupressDefaut(result);
                            if (!result.Contains("ERROR"))
                            {
                                value = valueSto;
                            }
                            else
                            {
                                SerialPort.SetError("ERROR SEND SMS FORMAT TEXT FROM STORAGE " + value.ToString());
                            }
                        }
                    }
                    else
                    {
                        if (SaveMessage)
                        {
                            SerialPort.SetError("ERROR WRITE SMS FORMAT TEXT IN STORAGE");
                        }
                        else
                        {
                            SerialPort.SetError("ERROR SEND SMS FORMAT TEXT");
                        }
                    }
                }
            }
            catch (Exception e)
            {
                SerialPort.SetError(e.Message);
                return -1;
            }
            if (SerialPort.Error != "")
            {
                return -1;
            }
            return value;
        }

        static public bool SMSHeaderOn(Modem SerialPort)
        {
            string result = "";
            try
            {
                SerialPort.SendCommand(ATCOMMAND.EchoOff);
                result = SerialPort.SendCommand(ATCOMMAND.SMSShowHead_CMD + "=1");
                result = SupressDefaut(result);
                if (result.Contains("ERROR"))
                {
                    SerialPort.SetError("ERROR WRITE SMS HEAD ON");
                }
            }
            catch (Exception e)
            {
                SerialPort.SetError(e.Message);
                return false;
            }
            if (SerialPort.Error == "")
            {
                return true;
            }
            return false;
        }

        static public bool AnaliseModemCMD(Modem SerialPort, AnalyzerCMDEnum CMD)
        {
            bool ret = false;
            string result = "";
            try
            {
                SerialPort.SendCommand(ATCOMMAND.EchoOff);
                switch (CMD)
                {
                    case AnalyzerCMDEnum.Model:
                        {
                            result = SerialPort.SendCommand(ATCOMMAND.Model_CMD + ATCOMMAND.ExistCommand);
                            if (!result.Contains("ERROR"))
                            {
                                ret = true;
                            }
                        }
                        break;
                    case AnalyzerCMDEnum.LineIdentification:
                        {
                            result = SerialPort.SendCommand(ATCOMMAND.LineIdentification_CMD + ATCOMMAND.ExistCommand);
                            if (!result.Contains("ERROR"))
                            {
                                ret = true;
                            }
                        }
                        break;
                    case AnalyzerCMDEnum.IndicatorControl:
                        {
                            result = SerialPort.SendCommand(ATCOMMAND.IndicatorControl_CMD + ATCOMMAND.ExistCommand);
                            if (!result.Contains("ERROR"))
                            {
                                ret = true;
                            }
                        }
                        break;
                    case AnalyzerCMDEnum.ActiveStatus:
                        {
                            result = SerialPort.SendCommand(ATCOMMAND.ActiveStatus_CMD + ATCOMMAND.ExistCommand);
                            if (!result.Contains("ERROR"))
                            {
                                ret = true;
                            }
                        }
                        break;
                    case AnalyzerCMDEnum.PrefOperator:
                        {
                            result = SerialPort.SendCommand(ATCOMMAND.PreferredOperatorValue);
                            if (!result.Contains("ERROR"))
                            {
                                ret = true;
                            }
                        }
                        break;
                    case AnalyzerCMDEnum.Battery:
                        {
                            result = SerialPort.SendCommand(ATCOMMAND.BatteryLevel_CMD + ATCOMMAND.ExistCommand);
                            if (!result.Contains("ERROR"))
                            {
                                ret = true;
                            }
                        }
                        break;
                    case AnalyzerCMDEnum.Sginal:
                        {
                            result = SerialPort.SendCommand(ATCOMMAND.SignalQuality_CMD + ATCOMMAND.ExistCommand);
                            if (!result.Contains("ERROR"))
                            {
                                ret = true;
                            }
                        }
                        break;
                    case AnalyzerCMDEnum.Alarms:
                        {
                            result = SerialPort.SendCommand(ATCOMMAND.Alarm_CMD + ATCOMMAND.ExistCommand);
                            if (!result.Contains("ERROR"))
                            {
                                ret = true;
                            }
                        }
                        break;
                    case AnalyzerCMDEnum.Clock:
                        {
                            result = SerialPort.SendCommand(ATCOMMAND.Clock_CMD + ATCOMMAND.ExistCommand);
                            if (!result.Contains("ERROR"))
                            {
                                ret = true;
                            }
                        }
                        break;
                    case AnalyzerCMDEnum.ChatSet:
                        {
                            result = SerialPort.SendCommand(ATCOMMAND.CharSets_CMD + ATCOMMAND.ExistCommand);
                            if (!result.Contains("ERROR"))
                            {
                                ret = true;
                            }
                        }
                        break;
                    case AnalyzerCMDEnum.Phonebook:
                        {
                            result = SerialPort.SendCommand(ATCOMMAND.PhoneBook_CMD + ATCOMMAND.ExistCommand);
                            if (!result.Contains("ERROR"))
                            {
                                ret = true;
                            }
                        }
                        break;
                    case AnalyzerCMDEnum.SMSFormat:
                        {
                            result = SerialPort.SendCommand(ATCOMMAND.SMSFormat_CMD + ATCOMMAND.ExistCommand);
                            if (!result.Contains("ERROR"))
                            {
                                ret = true;
                            }
                        }
                        break;
                    case AnalyzerCMDEnum.SMSStorage:
                        {
                            result = SerialPort.SendCommand(ATCOMMAND.SMSStorage_CMD + ATCOMMAND.ExistCommand);
                            if (!result.Contains("ERROR"))
                            {
                                ret = true;
                            }
                        }
                        break;
                    case AnalyzerCMDEnum.SMSAdress:
                        {
                            result = SerialPort.SendCommand(ATCOMMAND.SMSAdressService_CMD + ATCOMMAND.ExistCommand);
                            if (!result.Contains("ERROR"))
                            {
                                ret = true;
                            }
                        }
                        break;
                    case AnalyzerCMDEnum.SMSHeard:
                        {
                            result = SerialPort.SendCommand(ATCOMMAND.SMSShowHead_CMD + ATCOMMAND.ExistCommand);
                            if (!result.Contains("ERROR"))
                            {
                                ret = true;
                            }
                        }
                        break;
                    case AnalyzerCMDEnum.SMSIndicator:
                        {
                            result = SerialPort.SendCommand(ATCOMMAND.SMSConfigIndications_CMD + ATCOMMAND.ExistCommand);
                            if (!result.Contains("ERROR"))
                            {
                                ret = true;
                            }
                        }
                        break;
                    case AnalyzerCMDEnum.SMSSaveSettings:
                        {
                            result = SerialPort.SendCommand(ATCOMMAND.SMSSaveSettings_CMD + ATCOMMAND.ExistCommand);
                            if (!result.Contains("ERROR"))
                            {
                                ret = true;
                            }
                        }
                        break;
                    case AnalyzerCMDEnum.SMSRestoreSettings:
                        {
                            result = SerialPort.SendCommand(ATCOMMAND.SMSRestoreSettings_CMD + ATCOMMAND.ExistCommand);
                            if (!result.Contains("ERROR"))
                            {
                                ret = true;
                            }
                        }
                        break;
                    case AnalyzerCMDEnum.SMSMessageService:
                        {
                            result = SerialPort.SendCommand(ATCOMMAND.SMSMessageService_CMD + ATCOMMAND.ExistCommand);
                            if (!result.Contains("ERROR"))
                            {
                                ret = true;
                            }
                        }
                        break;
                    case AnalyzerCMDEnum.SMSBroadcastMessage:
                        {
                            result = SerialPort.SendCommand(ATCOMMAND.SMSBroadcastMessage_CMD + ATCOMMAND.ExistCommand);
                            if (!result.Contains("ERROR"))
                            {
                                ret = true;
                            }
                        }
                        break;
                    case AnalyzerCMDEnum.SMSListMessage:
                        {
                            result = SerialPort.SendCommand(ATCOMMAND.SMSListMessage_CMD + ATCOMMAND.ExistCommand);
                            if (!result.Contains("ERROR"))
                            {
                                ret = true;
                            }
                        }
                        break;
                    case AnalyzerCMDEnum.SMSReadMessage:
                        {
                            result = SerialPort.SendCommand(ATCOMMAND.SMSReadMessage_CMD + ATCOMMAND.ExistCommand);
                            if (!result.Contains("ERROR"))
                            {
                                ret = true;
                            }
                        }
                        break;
                    case AnalyzerCMDEnum.SMSSendMessage:
                        {
                            result = SerialPort.SendCommand(ATCOMMAND.SMSSentMessage_CMD + ATCOMMAND.ExistCommand);
                            if (!result.Contains("ERROR"))
                            {
                                ret = true;
                            }
                        }
                        break;
                    case AnalyzerCMDEnum.SMSSendMessageStorage:
                        {
                            result = SerialPort.SendCommand(ATCOMMAND.SMSSentMessageStorage_CMD + ATCOMMAND.ExistCommand);
                            if (!result.Contains("ERROR"))
                            {
                                ret = true;
                            }
                        }
                        break;
                    case AnalyzerCMDEnum.SMSWriteMessageStorage:
                        {
                            result = SerialPort.SendCommand(ATCOMMAND.SMSWriteMessageStorage_CMD + ATCOMMAND.ExistCommand);
                            if (!result.Contains("ERROR"))
                            {
                                ret = true;
                            }
                        }
                        break;
                    case AnalyzerCMDEnum.SMSDeleteMessageStorage:
                        {
                            result = SerialPort.SendCommand(ATCOMMAND.SMSDeleteMessageStorage_CMD + ATCOMMAND.ExistCommand);
                            if (!result.Contains("ERROR"))
                            {
                                ret = true;
                            }
                        }
                        break;
                }
            }
            catch
            {
                ret = false;
            }
            return ret;
        }

        static public ModelATCommands AnaliseModemALLCMD(Modem SerialPort)
        {
            ModelATCommands ret = new ModelATCommands();
            ret.ActiveStatusCMD = AnaliseModemCMD(SerialPort, AnalyzerCMDEnum.ActiveStatus);
            ret.AlarmCMD = AnaliseModemCMD(SerialPort, AnalyzerCMDEnum.Alarms);
            ret.BatteryLevelCMD = AnaliseModemCMD(SerialPort, AnalyzerCMDEnum.Battery);
            ret.CharSetsCMD = AnaliseModemCMD(SerialPort, AnalyzerCMDEnum.ChatSet);
            ret.ClockCMD = AnaliseModemCMD(SerialPort, AnalyzerCMDEnum.Clock);
            ret.IndicatorControlCMD = AnaliseModemCMD(SerialPort, AnalyzerCMDEnum.IndicatorControl);
            ret.LineIdentificationCMD = AnaliseModemCMD(SerialPort, AnalyzerCMDEnum.LineIdentification);
            ret.ModelCMD = AnaliseModemCMD(SerialPort, AnalyzerCMDEnum.Model);
            ret.PhoneBookCMD = AnaliseModemCMD(SerialPort, AnalyzerCMDEnum.Phonebook);
            ret.PreferredOperatorCMD = AnaliseModemCMD(SerialPort, AnalyzerCMDEnum.PrefOperator);
            ret.SignalQualityCMD = AnaliseModemCMD(SerialPort, AnalyzerCMDEnum.Sginal);
            ret.SMSAdressServiceCMD = AnaliseModemCMD(SerialPort, AnalyzerCMDEnum.SMSAdress);
            ret.SMSConfigIndicationsCMD = AnaliseModemCMD(SerialPort, AnalyzerCMDEnum.SMSIndicator);
            ret.SMSFormatCMD = AnaliseModemCMD(SerialPort, AnalyzerCMDEnum.SMSFormat);
            ret.SMSShowHeadCMD = AnaliseModemCMD(SerialPort, AnalyzerCMDEnum.SMSHeard);
            ret.SMSStoragesCMD = AnaliseModemCMD(SerialPort, AnalyzerCMDEnum.SMSStorage);
            ret.SMSSaveSettingsCMD = AnaliseModemCMD(SerialPort, AnalyzerCMDEnum.SMSSaveSettings);
            ret.SMSRestoreSettingsCMD = AnaliseModemCMD(SerialPort, AnalyzerCMDEnum.SMSRestoreSettings);
            ret.SMSMessageServiceCMD = AnaliseModemCMD(SerialPort, AnalyzerCMDEnum.SMSMessageService);
            ret.SMSBroadcastMessageCMD = AnaliseModemCMD(SerialPort, AnalyzerCMDEnum.SMSBroadcastMessage);
            ret.SMSListMessageCMD = AnaliseModemCMD(SerialPort, AnalyzerCMDEnum.SMSListMessage);
            ret.SMSReadMessageCMD = AnaliseModemCMD(SerialPort, AnalyzerCMDEnum.SMSReadMessage);
            ret.SMSSendMessageCMD = AnaliseModemCMD(SerialPort, AnalyzerCMDEnum.SMSSendMessage);
            ret.SMSSendMessageStorageCMD = AnaliseModemCMD(SerialPort, AnalyzerCMDEnum.SMSSendMessageStorage);
            ret.SMSWriteMessageStorageCMD = AnaliseModemCMD(SerialPort, AnalyzerCMDEnum.SMSWriteMessageStorage);
            ret.SMSDeleteMessageStorageCMD = AnaliseModemCMD(SerialPort, AnalyzerCMDEnum.SMSDeleteMessageStorage);

            return ret;
        }

        static public bool SMSIndications(Modem SerialPort, int Mode, int Delivery, int Receiver, int Report, int bufferunsolicited)
        {
            bool ret = false;
            string result = "";
            try
            {
                SerialPort.SendCommand(ATCOMMAND.EchoOff);
                result = SerialPort.SendCommand(ATCOMMAND.SMSConfigIndications_CMD + "=" + Mode.ToString() + "," + Delivery.ToString() + "," + Receiver.ToString() + "," + Report.ToString() + "," + bufferunsolicited.ToString());
                result = SupressDefaut(result);
                if (result.Contains("ERROR"))
                {
                    SerialPort.SetError("ERROR WRITE SMS Indications");
                }
                else
                {
                    ret = true;
                }
            }
            catch (Exception e)
            {
                SerialPort.SetError(e.Message);
                ret = false;
            }
            if (SerialPort.Error == "")
            {
                ret = true;
            }
            return ret;
        }

        static public bool SMSHeaderOff(Modem SerialPort)
        {
            string result = "";
            try
            {
                SerialPort.SendCommand(ATCOMMAND.EchoOff);
                result = SerialPort.SendCommand(ATCOMMAND.SMSShowHead_CMD + "=0");
                result = SupressDefaut(result);
                if (result.Contains("ERROR"))
                {
                    SerialPort.SetError("ERROR WRITE SMS HEAD OFF");
                }
            }
            catch (Exception e)
            {
                SerialPort.SetError(e.Message);
                return false;
            }
            if (SerialPort.Error == "")
            {
                return true;
            }
            return false;
        }

        static public bool SMSSaveSettings(Modem SerialPort,int Profile)
        {
            string result = "";
            try
            {
                SerialPort.SendCommand(ATCOMMAND.EchoOff);
                result = SerialPort.SendCommand(ATCOMMAND.SMSSaveSettings_CMD + "=" + Profile);
                result = SupressDefaut(result);
                if (result.Contains("ERROR"))
                {
                    SerialPort.SetError("ERROR SAVE SETTINGS SMS");
                }
            }
            catch (Exception e)
            {
                SerialPort.SetError(e.Message);
                return false;
            }
            if (SerialPort.Error == "")
            {
                return true;
            }
            return false;
        }

        static public bool SMSRestoreSettings(Modem SerialPort)
        {
            return SMSRestoreSettings(SerialPort, -1);
        }

        static public bool SMSRestoreSettings(Modem SerialPort, int Profile)
        {
            string result = "";
            try
            {
                SerialPort.SendCommand(ATCOMMAND.EchoOff);
                if (Profile < 0)
                {
                    result = SerialPort.SendCommand(ATCOMMAND.SMSRestoreSettings_CMD);
                }
                else
                {
                    result = SerialPort.SendCommand(ATCOMMAND.SMSRestoreSettings_CMD + "=" + Profile);
                }
                result = SupressDefaut(result);
                if (result.Contains("ERROR"))
                {
                    SerialPort.SetError("ERROR RESTORE SETTINGS SMS");
                }
            }
            catch (Exception e)
            {
                SerialPort.SetError(e.Message);
                return false;
            }
            if (SerialPort.Error == "")
            {
                return true;
            }
            return false;
        }

        static public SMSService SMSGetMessageService(Modem SerialPort)
        {
            SMSService ret = new SMSService();
            string result = "";
            try
            {
                SerialPort.SendCommand(ATCOMMAND.EchoOff);
                result = SerialPort.SendCommand(ATCOMMAND.SMSMessageService_CMD + ATCOMMAND.ExistCommand);
                if (!result.Contains("ERROR"))
                {
                    result = SupressDefaut(result);
                    result = result.Replace("(", "");
                    result = result.Replace(")", "");
                    string[] param = result.Split(new char[]{','}, StringSplitOptions.RemoveEmptyEntries);
                    ret.GSMmodes = new int[param.Length];
                    for (int i = 0; i < param.Length; i++)
                    {
                        ret.GSMmodes[i] = int.Parse(param[i].Trim());
                    }
                    result = SerialPort.SendCommand(ATCOMMAND.SMSMessageService_CMD + "?");
                }
                if (!result.Contains("ERROR"))
                {
                    result = SupressDefaut(result);
                    string[] param = result.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                    ret.GSMmode = int.Parse(param[0].Trim());
                    ret.GSMmt = param[1].Trim()=="1"?true:false;
                    ret.GSMmo = param[2].Trim() == "1" ? true : false;
                    ret.GSMbm = param[3].Trim() == "1" ? true : false;
                }
                else
                {
                    SerialPort.SetError("ERROR READ MESSAGE SERVICE SMS");
                }
            }
            catch (Exception e)
            {
                SerialPort.SetError(e.Message);
            }
            return ret;
        }

        static public SMSService SMSsetMessageService(Modem SerialPort, int Mode)
        {
            SMSService ret = new SMSService();
            string result = "";
            try
            {
                SerialPort.SendCommand(ATCOMMAND.EchoOff);
                result = SerialPort.SendCommand(ATCOMMAND.SMSMessageService_CMD + ATCOMMAND.ExistCommand);
                if (!result.Contains("ERROR"))
                {
                    result = SupressDefaut(result);
                    result = result.Replace("(", "");
                    result = result.Replace(")", "");
                    string[] param = result.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                    ret.GSMmodes = new int[param.Length];
                    for (int i = 0; i < param.Length; i++)
                    {
                        ret.GSMmodes[i] = int.Parse(param[i].Trim());
                    }
                    result = SerialPort.SendCommand(ATCOMMAND.SMSMessageService_CMD + "=" + Mode);
                }
                if (!result.Contains("ERROR"))
                {
                    result = SupressDefaut(result);
                    string[] param = result.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                    ret.GSMmode = Mode;
                    ret.GSMmt = param[1].Trim() == "1" ? true : false;
                    ret.GSMmo = param[2].Trim() == "1" ? true : false;
                    ret.GSMbm = param[3].Trim() == "1" ? true : false;
                }
                else
                {
                    SerialPort.SetError("ERROR READ MESSAGE SERVICE SMS");
                }
            }
            catch (Exception e)
            {
                SerialPort.SetError(e.Message);
            }
            return ret;
        }

        static public int?[] SMSGetBroadcastMessage(Modem SerialPort)
        {
            string result = "";
            int?[] ret = new int?[0];
            try
            {
                SerialPort.SendCommand(ATCOMMAND.EchoOff);
                result = SerialPort.SendCommand(ATCOMMAND.SMSBroadcastMessage_CMD + ATCOMMAND.ExistCommand);
                result = SupressDefaut(result);
                if (!result.Contains("ERROR"))
                {
                    result = result.Replace("(", "");
                    result = result.Replace(")", "");
                    string[] param = result.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                    ret = new int?[param.Length];
                    for (int i = 0; i < param.Length; i++)
                    {
                        ret[i] = int.Parse(param[i].Trim());
                    }
                }
                else
                {
                    SerialPort.SetError("ERROR READ BROADCAST MESSAGE SMS");
                }
            }
            catch (Exception e)
            {
                SerialPort.SetError(e.Message);
            }
            if (SerialPort.Error != "")
            {
                ret = new int?[0];
            }
            return ret;
        }

        static public bool SMSSetBroadcastMessage(Modem SerialPort,int Mode)
        {
            string result = "";
            bool ret = true;
            try
            {
                SerialPort.SendCommand(ATCOMMAND.EchoOff);
                result = SerialPort.SendCommand(ATCOMMAND.SMSBroadcastMessage_CMD + "=" + Mode);
                result = SupressDefaut(result);
                if (!result.Contains("ERROR"))
                {
                    ret = true;
                }
                else
                {
                    SerialPort.SetError("ERROR WRITE BROADCAST MESSAGE SMS");
                }
            }
            catch (Exception e)
            {
                SerialPort.SetError(e.Message);
            }
            return ret;
        }

        static public bool SMSDeleteMessage(Modem SerialPort,int index)
        {
            string result = "";
            bool ret = true;
            try
            {
                SerialPort.SendCommand(ATCOMMAND.EchoOff);
                result = SerialPort.SendCommand(ATCOMMAND.SMSDeleteMessageStorage_CMD + "=" + index);
                result = SupressDefaut(result);
                if (!result.Contains("ERROR"))
                {
                    ret = true;
                }
                else
                {
                    SerialPort.SetError("ERROR DELETE MESSAGE SMS");
                }
            }
            catch (Exception e)
            {
                SerialPort.SetError(e.Message);
            }
            return ret;
        }

        static public bool SetDateTime(Modem SerialPort, string Datetime)
        {
            string result = "";
            try
            {
                SerialPort.SendCommand(ATCOMMAND.EchoOff);
                result = SerialPort.SendCommand(ATCOMMAND.ClockWrite + "\"" + Datetime + "\"");
                result = SupressDefaut(result);
                if (result.Contains("ERROR"))
                {
                    SerialPort.SetError("ERROR WRITE DATE AND TIME");
                }
            }
            catch (Exception e)
            {
                SerialPort.SetError(e.Message);
                return false;
            }
            if (SerialPort.Error == "")
            {
                return true;
            }
            return false;
        }

        static public string GetDateTime(Modem SerialPort)
        {
            string result = "";
            try
            {
                SerialPort.SendCommand(ATCOMMAND.EchoOff);
                result = SerialPort.SendCommand(ATCOMMAND.ClockValue);
                result = SupressDefaut(result);
                result = SupressDelimtStr(result);
                if (result.Contains("ERROR"))
                {
                    SerialPort.SetError("ERROR READ DATE AND TIME");
                    result = "";
                }
            }
            catch (Exception e)
            {
                SerialPort.SetError(e.Message);
                result = "";
            }
            return result.Trim();
        }

        static public List<GSMAlarm> GetAlarms(Modem SerialPort)
        {
            List<GSMAlarm> result = new List<GSMAlarm>();
            try
            {
                SerialPort.SendCommand(ATCOMMAND.EchoOff);
                string output = SerialPort.SendCommand(ATCOMMAND.AlarmRead);
                if (!output.Contains("ERROR"))
                {
                    output = SupressCR(output);
                    output = SupressDelimtStr(output);
                    output = output.Replace("OK", "");
                    string[] param = output.Split(new string[] {ATCOMMAND.StrAlarmDelimit},StringSplitOptions.RemoveEmptyEntries);
                    foreach (string item in param)
                    {
                        string[] alm = item.Split(',');
                        GSMAlarm alarm = new GSMAlarm();
                        alarm.Index = int.Parse(alm[2].Trim());
                        alarm.Hours = int.Parse(alm[1].Substring(0, 2).Trim());
                        alarm.Minutes = int.Parse(alm[1].Substring(3, 2).Trim());
                        int qtd = 0;
                        for (int i = 5; i < alm.Length; i++)
                        {
                            if (alm[i].Trim() == "1")
                            {
                                qtd++;
                                alarm.Mon = true;
                            }
                            else if (alm[i].Trim() == "2")
                            {
                                qtd++;
                                alarm.Tus = true;
                            }
                            else if (alm[i].Trim() == "3")
                            {
                                qtd++;
                                alarm.Wed = true;
                            }
                            else if (alm[i].Trim() == "4")
                            {
                                qtd++;
                                alarm.Thu = true;
                            }
                            else if (alm[i].Trim() == "5")
                            {
                                qtd++;
                                alarm.Fri = true;
                            }
                            else if (alm[i].Trim() == "6")
                            {
                                qtd++;
                                alarm.Sat = true;
                            }
                            else if (alm[i].Trim() == "7")
                            {
                                qtd++;
                                alarm.Sun = true;
                            }
                        }
                        alarm.Repeat = RepeatAlamrEnum.Once;
                        if (qtd == 7)
                        {
                            alarm.Repeat = RepeatAlamrEnum.EveryDay;
                        }
                        else if (qtd > 0)
                        {
                            alarm.Repeat = RepeatAlamrEnum.Days;
                        }
                        result.Add(alarm);
                    }
                }
                else
                {
                    SerialPort.SetError("ERROR READ ALARMS");
                }
            }
            catch (Exception e)
            {
                SerialPort.SetError(e.Message);
                result = new List<GSMAlarm>();
            }
            return result;
        }

        static public bool SetAlarm(Modem SerialPort, GSMAlarm Alarm)
        {
            string result = "";
            try
            {
                SerialPort.SendCommand(ATCOMMAND.EchoOff);
                DateTime Dtref = System.DateTime.Now;
                Dtref = new DateTime(Dtref.Year, Dtref.Month, Dtref.Day, Alarm.Hours, Alarm.Minutes, 0);
                string param = "\"00/00/00,";
                param += Dtref.ToString("HH:mm:ss") + "\",";
                param += Alarm.Index.ToString() + ",";
                switch (Alarm.Repeat)
                {
                    case RepeatAlamrEnum.Once:
                        param += "\"\" , \"\",";
                        break;
                    case RepeatAlamrEnum.EveryDay:
                        param += " ,\"1\",";
                        break;
                    case RepeatAlamrEnum.Days:
                        param += " ,\"2\",";
                        break;
                }
                param += "\"";
                if (Alarm.Mon || Alarm.Repeat != RepeatAlamrEnum.Days)
                {
                    param += "1,";
                }
                if (Alarm.Tus || Alarm.Repeat != RepeatAlamrEnum.Days)
                {
                    param += "2,";
                }
                if (Alarm.Wed || Alarm.Repeat != RepeatAlamrEnum.Days)
                {
                    param += "3,";
                }
                if (Alarm.Thu || Alarm.Repeat != RepeatAlamrEnum.Days)
                {
                    param += "4,";
                }
                if (Alarm.Fri || Alarm.Repeat != RepeatAlamrEnum.Days)
                {
                    param += "5,";
                }
                if (Alarm.Sat || Alarm.Repeat != RepeatAlamrEnum.Days)
                {
                    param += "6,";
                }
                if (Alarm.Sun || Alarm.Repeat != RepeatAlamrEnum.Days)
                {
                    param += "7,";
                }
                if (param.EndsWith(","))
                {
                    param = param.Substring(0,param.Length-1);
                }
                param += "\"";
                result = SerialPort.SendCommand(ATCOMMAND.AlarmWrite + param);
                if (result.Contains("ERROR"))
                {
                    result = "ERROR";
                    SerialPort.SetError("ERROR WRITE ALARMS");
                }
            }
            catch (Exception e)
            {
                result = "ERROR";
                SerialPort.SetError(e.Message);
            }
            if (result == "ERROR")
            {
                return false;
            }
            return true;
        }

        static public bool DeleteAlarm(Modem SerialPort,int Index)
        {
            string result = "";
            try
            {
                SerialPort.SendCommand(ATCOMMAND.EchoOff);
                result = SerialPort.SendCommand(ATCOMMAND.AlarmDelete + Index.ToString());
                if (!result.Contains("ERROR"))
                {
                    result = result.Trim();
                }
                else
                {
                    result = "ERROR";
                    SerialPort.SetError("ERROR DELETE ALARM" + Index.ToString());
                }
            }
            catch (Exception e)
            {
                SerialPort.SetError(e.Message);
                result = "ERROR";
            }
            if (result == "ERROR")
            {
                return false;
            }
            return true;
        }

        static public bool SetCharSet(Modem SerialPort, string CharSet)
        {
            string result = "";
            try
            {
                SerialPort.SendCommand(ATCOMMAND.EchoOff);
                result = SerialPort.SendCommand(ATCOMMAND.CharSetWrite + "\"" + CharSet + "\"");
                if (!result.Contains("ERROR"))
                {
                    result = result.Trim();
                }
                else
                {
                    result = "ERROR";
                    SerialPort.SetError("ERROR SET CHAR SET" + CharSet);
                }
            }
            catch (Exception e)
            {
                SerialPort.SetError(e.Message);
                result = "ERROR";
            }
            if (result == "ERROR")
            {
                return false;
            }
            return true;
        }

        static public ActiveStatusEnum GetActiveStatus(Modem SerialPort)
        {
            ActiveStatusEnum result = ActiveStatusEnum.unknown;
            try
            {
                SerialPort.SendCommand(ATCOMMAND.EchoOff);
                string output = SerialPort.SendCommand(ATCOMMAND.ActiveStatus_CMD);
                output = SupressDefaut(output);
                if (!output.Contains("ERROR"))
                {
                    if (output == "0")
                    {
                        result = ActiveStatusEnum.Ready;
                    }
                    else if (output == "1")
                    {
                        result = ActiveStatusEnum.Unavailable;
                    }
                    else if (output == "2")
                    {
                        result = ActiveStatusEnum.unknown;
                    }
                    else if (output == "3")
                    {
                        result = ActiveStatusEnum.Ringing;
                    }
                    else if (output == "4")
                    {
                        result = ActiveStatusEnum.call;
                    }
                    else if (output == "5")
                    {
                        result = ActiveStatusEnum.asleep;
                    }
                }
                else
                {
                    result = ActiveStatusEnum.Error;
                    SerialPort.SetError("ERROR READ ACTIVE STATUS");
                }
            }
            catch (Exception e)
            {
                result = ActiveStatusEnum.Error;
                SerialPort.SetError(e.Message);
            }
            return result;
        }

        static public PhoneBookMaxLength GetPbookSIMMaxLength(Modem SerialPort)
        {
            PhoneBookMaxLength ret = new PhoneBookMaxLength();
            string result = "";
            try
            {
                SerialPort.SendCommand(ATCOMMAND.EchoOff);
                result = SerialPort.SendCommand(ATCOMMAND.PhoneBookStorageSIM);
                if (!result.Contains("ERROR"))
                {
                    result = SerialPort.SendCommand(ATCOMMAND.PhoneBookStorageFieldsMaxlenght);
                    result = SupressDefaut(result);
                    if (!result.Contains("ERROR"))
                    {
                        string[] param = result.Split(',');
                        ret.Number = int.Parse(param[1].Trim());
                        ret.Name = int.Parse(param[2].Trim());
                    }
                    else
                    {
                        SerialPort.SetError("ERROR READ SIM MAXLENGTH PHONEBOOK ");
                    }
                }
                else
                {
                    SerialPort.SetError("ERROR READ SIM MAXLENGTH PHONEBOOK ");
                }
            }
            catch (Exception e)
            {
                SerialPort.SetError(e.Message);
            }
            return ret;
        }

        static public PhoneBookMaxLength GetPbookMEMMaxLength(Modem SerialPort)
        {
            PhoneBookMaxLength ret = new PhoneBookMaxLength();
            string result = "";
            try
            {
                SerialPort.SendCommand(ATCOMMAND.EchoOff);
                result = SerialPort.SendCommand(ATCOMMAND.PhoneBookStorageMEM);
                if (!result.Contains("ERROR"))
                {
                    result = SerialPort.SendCommand(ATCOMMAND.PhoneBookStorageFieldsMaxlenght);
                    result = SupressDefaut(result);
                    if (!result.Contains("ERROR"))
                    {
                        string[] param = result.Split(',');
                        ret.Number = int.Parse(param[1].Trim());
                        ret.Name = int.Parse(param[2].Trim());
                    }
                    else
                    {
                        SerialPort.SetError("ERROR READ MEM MAXLENGTH PHONEBOOK ");
                    }
                }
                else
                {
                    SerialPort.SetError("ERROR READ MEM MAXLENGTH PHONEBOOK ");
                }
            }
            catch (Exception e)
            {
                SerialPort.SetError(e.Message);
            }
            return ret;
        }

        static public int FindFreeBook(Modem SerialPort,StorageReadEnum Storage)
        {

            int ret = -1;
            string result = "";
            try
            {
                SerialPort.SendCommand(ATCOMMAND.EchoOff);
                RangerValue Ranger = null; 
                if (Storage == StorageReadEnum.Phone)
                {
                    Ranger = GetMEMPhoneRange(SerialPort);
                    if (SerialPort.Error != "")
                    {
                        return ret - 1;
                    }
                    result = SerialPort.SendCommand(ATCOMMAND.PhoneBookStorageMEM);
                }
                else if (Storage == StorageReadEnum.SIM)
                {
                    Ranger = GetSIMPhoneRange(SerialPort);
                    if (SerialPort.Error != "")
                    {
                        return ret - 1;
                    }
                    result = SerialPort.SendCommand(ATCOMMAND.PhoneBookStorageSIM);
                }
                else
                {
                    return -1;
                }
                if (!result.Contains("ERROR"))
                {
                    int pos = Ranger.Min;
                    while (pos <= Ranger.Max)
                    {
                        result = SerialPort.SendCommand(ATCOMMAND.PhoneBookRead + pos.ToString());
                        if (result.Contains("ERROR"))
                        {
                            break;
                        }
                        result = SupressDefaut(result);
                        result = SupressDelimtStr(result);
                        if (result == "")
                        {
                            ret = pos;
                            break;

                        }
                        pos++;
                    }
                }
            }
            catch (Exception e)
            {
                SerialPort.SetError(e.Message);
            }
            return ret;
        }

        static public int AddPBookMEM(Modem SerialPort,string Name, String Number)
        {
            int Index = FindFreeBook(SerialPort, StorageReadEnum.Phone);
            if (Index < 0)
            {
                return Index;
            }
            string result = "";
            try
            {
                SerialPort.SendCommand(ATCOMMAND.EchoOff);
                result = SerialPort.SendCommand(ATCOMMAND.PhoneBookStorageMEM);
                if (!result.Contains("ERROR"))
                {
                    string cmd = Index.ToString() + ", \"" + Number + "\", 129, \"" + Name + "\"";
                    result = SerialPort.SendCommand(ATCOMMAND.PhoneBookWrite + cmd);
                    bool ok = result.Contains("OK");
                    if (!ok)
                    {
                        SerialPort.SetError("ERROR ADD MEM PHONEBOOK ");
                    }
                }
                else
                {
                    SerialPort.SetError("ERROR ADD MEM PHONEBOOK ");
                }
            }
            catch (Exception e)
            {
                SerialPort.SetError(e.Message);
            }
            return Index;
        }

        static public bool UpadatePBookMEM(Modem SerialPort,string Index, string Name, String Number)
        {
            bool ret = false;
            string result = "";
            try
            {
                SerialPort.SendCommand(ATCOMMAND.EchoOff);
                result = SerialPort.SendCommand(ATCOMMAND.PhoneBookStorageMEM);
                if (!result.Contains("ERROR"))
                {
                    string cmd = Index + ", \"" + Number + "\", 129, \"" + Name + "\"";
                    result = SerialPort.SendCommand(ATCOMMAND.PhoneBookWrite + cmd);
                    ret = result.Contains("OK");
                    if (!ret)
                    {
                        SerialPort.SetError("ERROR UPDATE MEM PHONEBOOK ");
                    }
                }
                else
                {
                    SerialPort.SetError("ERROR UPDATE MEM PHONEBOOK ");
                }
            }
            catch (Exception e)
            {
                SerialPort.SetError(e.Message);
            }
            return ret;
        }

        static public bool DeletePBookMEM(Modem SerialPort, string Index)
        {
            bool ret = false;
            string result = "";
            try
            {
                SerialPort.SendCommand(ATCOMMAND.EchoOff);
                result = SerialPort.SendCommand(ATCOMMAND.PhoneBookStorageMEM);
                if (!result.Contains("ERROR"))
                {
                    result = SerialPort.SendCommand(ATCOMMAND.PhoneBookWrite + Index);
                    ret = result.Contains("OK");
                    if (!ret)
                    {
                        SerialPort.SetError("ERROR DELETE MEM PHONEBOOK ");
                    }
                }
                else
                {
                    SerialPort.SetError("ERROR DELETE MEM PHONEBOOK ");
                }
            }
            catch (Exception e)
            {
                SerialPort.SetError(e.Message);
            }
            return ret;
        }

        static public int AddPBookSIM(Modem SerialPort, string Name, String Number)
        {
            int Index = FindFreeBook(SerialPort, StorageReadEnum.SIM);
            if (Index < 0)
            {
                return Index;
            }
            string result = "";
            try
            {
                SerialPort.SendCommand(ATCOMMAND.EchoOff);
                result = SerialPort.SendCommand(ATCOMMAND.PhoneBookStorageSIM);
                if (!result.Contains("ERROR"))
                {
                    string cmd = Index.ToString() +  ", \"" + Number + "\", 129, \"" + Name + "\"";
                    result = SerialPort.SendCommand(ATCOMMAND.PhoneBookWrite + cmd);
                    bool ok = result.Contains("OK");
                    if (!ok)
                    {
                        SerialPort.SetError("ERROR ADD SIM PHONEBOOK ");
                    }
                }
                else
                {
                    SerialPort.SetError("ERROR ADD SIM PHONEBOOK ");
                }
            }
            catch (Exception e)
            {
                SerialPort.SetError(e.Message);
            }
            return Index;
        }

        static public bool UpdatePBookSIM(Modem SerialPort,string Index, string Name, String Number)
        {
            bool ret = false;
            string result = "";
            try
            {
                SerialPort.SendCommand(ATCOMMAND.EchoOff);
                result = SerialPort.SendCommand(ATCOMMAND.PhoneBookStorageSIM);
                if (!result.Contains("ERROR"))
                {
                    string cmd = Index + ", \"" + Number + "\", 129, \"" + Name + "\"";
                    result = SerialPort.SendCommand(ATCOMMAND.PhoneBookWrite + cmd);
                    ret = result.Contains("OK");
                    if (!ret)
                    {
                        SerialPort.SetError("ERROR UPDATE SIM PHONEBOOK ");
                    }
                }
                else
                {
                    SerialPort.SetError("ERROR UPDATE SIM PHONEBOOK ");
                }
            }
            catch (Exception e)
            {
                SerialPort.SetError(e.Message);
            }
            return ret;
        }

        static public bool DeletePBookSIM(Modem SerialPort, string Index)
        {
            bool ret = false;
            string result = "";
            try
            {
                SerialPort.SendCommand(ATCOMMAND.EchoOff);
                result = SerialPort.SendCommand(ATCOMMAND.PhoneBookStorageSIM);
                if (!result.Contains("ERROR"))
                {
                    result = SerialPort.SendCommand(ATCOMMAND.PhoneBookWrite + Index);
                    ret = result.Contains("OK");
                    if (!ret)
                    {
                        SerialPort.SetError("ERROR DELETE SIM PHONEBOOK ");
                    }
                }
                else
                {
                    SerialPort.SetError("ERROR DELETE SIM PHONEBOOK ");
                }
            }
            catch (Exception e)
            {
                SerialPort.SetError(e.Message);
            }
            return ret;
        }

    }
}
